package email
import activity.*

class EmailService {
    def mailService//系統插件
    def SYSEmail = "activity@nlpi.edu.tw" //activity@nlpi.edu.tw
    //"正取報名","候補報名","待審報名" in frontController/dataSave
    //"自行取消" in frontController/regQueryCancel
    //"候補補到" in register/changeStandby
    //"報名審過","報名審拒" in register/edit 改狀態時發信

    def manualMail() {
        manualMail(null, null, null, null)
    }

    def manualMail(def informType, def event, def reader, def register) {



        //找出Manual，依done, active, schedule
        def query = Manual.where {
            //active == "Y" && done == "N" && schedule <= new Date()
        }
        def manuals = query.list()
        //決定對象
        println "Hello!123 Real Time"
        println "manuals.size:" + manuals.size()
        //找出Register，依event及recipient
        //決定主旨
        //決定內文
        //逐一發信及備份
    }
    
    def sendMail(def informType, def event, def reader, def register) {
        //找出相對應通知信
        def inform = Inform.findByTimingAndActive(informType, "Y")
        //指定寄送對象
        def subject = ''
        def content = ''
        def toUser = reader.email1
        def ccUser = ''
        if (!toUser) {//讀者沒Email寄備份信
            toUser = SYSEmail
            subject = '讀者沒Email' + informType + '信備份'
        }
        if (!inform) {//沒定義通知寄信給系統
            toUser = SYSEmail
            subject += informType + '信未定義備份'
            content = "registerID=" + register.id 
        } else {
            subject = inform.subject + "-" + event.name
            content = inform.content ?: ""
            content = genContent(content, event.serial, event, reader, register)
        }
        if (toUser != SYSEmail) {
            ccUser = SYSEmail
        }
        mail(toUser, ccUser, subject, content)
    }
    
    private String genContent(def content, def serial, def event, def reader, def register) {
        //取代信件代碼
        content = content.replace('#serial.name#', serial.name ?: '')
        content = content.replace('#event.name#', event.name ?: '')
        content = content.replace('#event.place#', event.place?.name ?: '')
        content = content.replace('#event.dateStart#', event.dateStart?.format("yyyy/MM/dd HH:mm") ?: '')
        content = content.replace('#event.dateEnd#', event.dateEnd?.format("yyyy/MM/dd HH:mm") ?: '')
        content = content.replace('#event.checkInStart#', event.checkInStart?.format("yyyy/MM/dd HH:mm") ?: '')
        content = content.replace('#event.checkInEnd#', event.checkInEnd?.format("yyyy/MM/dd HH:mm") ?: '')
        content = content.replace('#event.checkIn#', event.checkIn ?: '')
        content = content.replace('#reader.name#', reader.name ?: '')
        content = content.replace('#register.sysCode#', ''+register.sysCode ?: '')
        content = content.replace('#register.cancelCode#', register.cancelCode ?: '')
        //        content = inform.content.replace('#reader.meat#', reader.meat ?: '')
        //        content = inform.content.replace('#reader.sleep#', reader.sleep ?: '')
        return content
    }
    
    private def mail(def toUser, def bccUser, def title, def content) {
        try{
            if (bccUser == '') {
                mailService.sendMail {
                    to toUser
                    subject title
                    html content
                }
            } else {
                mailService.sendMail {
                    to toUser
                    bcc bccUser
                    subject title
                    html content
                }
            }
        } catch (Exception e) {
            println "Email Error: toUser:"+toUser+",title:"+title+",reason:"+e
        }
    }
    
    def ping() {
        def resultList = []
        def ipList = params.ip
        if (!ipList) {
            ipList = ["192.168.210.238", "192.168.210.239", "192.168.210.240", "192.168.210.241"]
        }
        for (ip in ipList) {
            if (!ip || ip.size() < 1) continue
            def timeOut = 3000
            def time = new Date()
            def status = InetAddress.getByName(ip).isReachable(timeOut)
            if (!status) {
                try {
                    mail(ip, time)
                } catch(all) {
                    println "Ping Error: " + ip + " at " + time
                }
            }
            resultList.add([ip:ip, status:status, time:time])
        }
        ([resultList: resultList])
    }
    
//    def mail(String ip, Date time) {
//        mailService.sendMail {
//            to "mars@nlpi.edu.tw"
//            subject "Ping Error: " + ip + " at " + time
//            html "Ping Error: " + ip + " at " + time
//        }
//    }    
}